package com.lcredu.proxy2;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author 黎长容
 * @date 2025-07-15 12:05
 */
public class VehicleProxy {
    //实现了Vehicle接口的被代理对象
    private Vehicle vehicle;

    public VehicleProxy(Vehicle vehicle) {
        this.vehicle = vehicle;
    }

    public Vehicle getProxy() {
        ClassLoader classLoader = vehicle.getClass().getClassLoader();
        Class<?>[] interfaces = vehicle.getClass().getInterfaces();
        InvocationHandler invocationHandler = new InvocationHandler() {

            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("交通工具开始了...");
                Object invoke = method.invoke(vehicle, args);
                System.out.println(invoke);
                System.out.println("交通工具停止了...");
                return invoke;
            }
        };

        Vehicle vehicle = (Vehicle) Proxy.newProxyInstance(classLoader, interfaces, invocationHandler);
        return vehicle;
    }
}
